package net.esj.background.struts2.web;

import java.util.Set;

import net.esj.background.manage.LoginManage;
import net.esj.background.manage.MenuManage;
import net.esj.background.struts2.view.easyui.AbstractBgAction;
import net.esj.background.support.AccessDepend;
import net.esj.background.support.multi.Portal;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class BackstageEntranceInterceptor extends AbstractInterceptor implements ApplicationContextAware{

	public static final  String ACTION_NON_AUTHORITATIVE = "nonAuth";
	
	public static final String ACTION_NAMESPACE_PREFIX = "/portal";
	
	private Set<AccessDepend> accesses;
	
	private ApplicationContext applicationContext;
	
	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
//		for(AccessDepend<ActionInvocation> acc : accesses){
//			if(!acc.canAccess(invocation)){
//				return ACTION_NON_AUTHORITATIVE;
//			}
//		}
		String uri = ServletActionContext.getRequest().getRequestURI();
		
		if(!uri.startsWith(ACTION_NAMESPACE_PREFIX)){
			return invocation.invoke();
		}
		Object o = invocation.getAction();
		if(! (o instanceof AbstractBgAction)){
			return invocation.invoke();
		}
		AbstractBgAction action = (AbstractBgAction) o;
		boolean has = false;
		for(Portal portal : Portal.getAll()){
			String ns = uri.substring(ACTION_NAMESPACE_PREFIX.length());
			if(ns.startsWith(portal.getNamespace())
					&& (action instanceof AbstractBgAction)){
				setBean( action, portal);
				has = true;
			}
		}
		if(!has){
			setBean( action, Portal.DEFAULT_PORTAL);
		}
		return invocation.invoke();
	}

	private void setBean(AbstractBgAction action,Portal portal) throws Exception{
		LoginManage loginManage = (LoginManage) applicationContext.getBean(portal.getLoginManageClass());
		MenuManage menuManage =(MenuManage) applicationContext.getBean(portal.getMenuManageClass());
		((AbstractBgAction)action).setPortal(portal);
		((AbstractBgAction)action).setMenuManage(menuManage);
		((AbstractBgAction)action).setLoginManage(loginManage);
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
}
